<?php

namespace app\staff\controller;

use app\common\controller\StaffBase;
use think\Db;

/**
 * 義工管理
 *
 * @icon fa fa-circle-o
 */
class Volunteer extends StaffBase
{
    
    /**
     * Volunteer模型对象
     * @var \app\admin\model\Volunteer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Volunteer;
        $this->view->assign("serviceTimeTypeList", $this->model->getServiceTimeTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 互助廣場指派義工
     */
    public function indexsss($ids = 0)
    {
        $task = db('help_task')->where(['id'=>$ids])->find();
        $user_id = $task['user_id'];
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);

        if ($this->request->isPost()) {
            $volunteer_id_post = input('post.volunteer_id');
            if ($volunteer_id_post) {
                $result = false;
                Db::startTrans();
                try {
                    $save = [];
                    $save['volunteer_id'] = $volunteer_id_post;
                    $save['distributiontime'] = time();
                    $save['status'] = '4';
                    $result = db('help_task')->where(['id'=>$ids])->update($save);
                    // 通知用戶
                    sendMessage(1,'您的求助訂單'.$task['task_no'].'已被接單','',$task['user_id'],2,$task['id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('指派成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            
            $this->success('操作成功');
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf = ['user.id'=>['neq',$user_id]];
            $list = $this->model
                    ->with(['user','volunteerspecialty'])
                    ->where(['volunteer.staff_id'=>$this->auth->id])
                    ->where($where)
                    ->where($where_buf)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 查看義工列表(用到的地方：【員工賬號添加，詳情，分配義工source = staff】【培訓任務，關懷任務source = tasks】)
     */
    public function indexs($ids = null)
    {
        $arr = explode(',', $ids);
        if ( !$arr[0] ) {
            $arr = [];
        }
        $arrs = [];
        foreach ($arr as $key => $value) {
            $arrs[] = (int)$value;
        }
        $this->assignconfig("arr", $arrs);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) { 
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf = ['volunteer.staff_id'=>$this->auth->id];
            $list = $this->model
                    ->with(['user','volunteerspecialty'])
                    ->where($where)
                    ->where($where_buf)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                // $region_address = db('region')->where(['id'=>$row->province])->value('name');
                // $city = db('region')->where(['id'=>$row->city])->value('name');
                // if ( $city ) {
                //     $region_address = $region_address.$city;
                //     $district = db('region')->where(['id'=>$row->district])->value('name');
                //     if ( $district ) {
                //         $region_address = $region_address.$district;
                //     }
                // }
                // $row->region_address = $region_address?$region_address:'';
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
